#!/bin/sh

### BEGIN INIT INFO
# Provides:          btsync
# Required-Start:    $local_fs $remote_fs $network
# Required-Stop:     $local_fs $remote_fs $network
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
### END INIT INFO

NAME=btsync
DAEMON=/usr/local/bin/$NAME
USER=root
STOP_TIMEOUT=30

[ -x $DAEMON ] || exit 0
HOMEDIR=`getent passwd $USER | cut -d: -f6`

. /lib/lsb/init-functions

script_install() {
    cp $0 /etc/init.d/$NAME
    chmod a+x /etc/init.d/$NAME
    update-rc.d $NAME defaults
    if [ ! -f $HOMEDIR/btsync.conf ]; then
	$DAEMON --dump-sample-config > $HOMEDIR/btsync.conf
	log_action_msg "Sample config generated at $HOMEDIR/btsync.conf"
	log_action_msg "Please edit config and restart script"
    fi
}

script_remove() {
    update-rc.d -f $NAME remove
    rm -f /etc/init.d/$NAME
}

start() {
    echo 16384 > /proc/sys/vm/min_free_kbytes
    start-stop-daemon --start --chuid $USER --background  \
	--exec $DAEMON -- --config $HOMEDIR/btsync.conf || log_end_msg $?
    log_end_msg 0
}

stop() {
	    start-stop-daemon --stop --quiet \
		--exec $DAEMON --retry $STOP_TIMEOUT \
		--oknodo || log_end_msg $?
	    log_end_msg 0
}

case "$1" in
    start)
	log_daemon_msg "Starting btsync daemon" "$NAME"
	start
    ;;
    stop)
	log_daemon_msg "Stopping btsync daemon" "$NAME"
	stop
    ;;
    restart)
	log_daemon_msg "Restarting btsync daemon" "$NAME"
	start-stop-daemon --stop --quiet \
	    --exec $DAEMON --retry $STOP_TIMEOUT \
	    --oknodo || log_end_msg $?
	start
    ;;
    install)
	script_install
    ;;
    status)
	status_of_proc "$DAEMON" "$NAME" && exit 0 || exit $?
    ;;
    remove)
	stop
	script_remove
    ;;
    *)
	log_action_msg "Usage: /etc/init.d/$NAME {start|stop|restart|install|remove|status}" || true
	exit 2
esac

exit $?
